package com.dzl.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.WelfareOrderEnum;
import com.dzl.order.pojo.WelfareOrder;
import com.dzl.order.pojo.WelfareOrderAddress;
import com.dzl.order.pojo.WelfareOrderGoods;
import com.dzl.order.pojo.dto.*;
import com.dzl.order.pojo.query.WelfareOrderQuery;
import com.dzl.order.pojo.vo.WelfareOrderDetailVo;
import com.dzl.order.pojo.vo.WelfareOrderParentVo;
import com.dzl.order.pojo.vo.WelfareOrderSupplierVo;
import com.dzl.order.service.WelfareOrderAddressService;
import com.dzl.order.service.WelfareOrderGoodsService;
import com.dzl.order.service.WelfareOrderService;
import com.dzl.supplier.pojo.WelfareSupplier;
import com.dzl.util.EmptyUtils;
import com.dzl.util.JsonResult;
import com.dzl.util.PageUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单表(WelfareOrder)表控制层
 * @author caobucao
 * @date 2021-05-21 11:36:29
 */
@RestController
@RequestMapping("/welfareOrder")
public class WelfareOrderController extends BaseController {

    @Autowired
    private WelfareOrderService service;
    @Autowired
    private WelfareOrderAddressService welfareOrderAddressService;
    @Autowired
    private WelfareOrderGoodsService welfareOrderGoodsService;

    /**
     * 获取各状态的订单数量
     * @param query 查询条件
     * @return com.dzl.util.JsonResult
     * @date 2021/5/26 17:55
     * @author caobucao
     */
    @GetMapping("getOrderCount")
    public JsonResult<List<Integer>> getOrderCount(WelfareOrderQuery query) {
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        if(query.getSupplierId()!=null && query.getSupplierId()==0){
            query.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
            query.setSupplierId(null);
        }
        List<Integer> list = service.getOrderCount(query);
        List<Integer> list_ = new ArrayList<>();
        list_.add(list.get(0));
        list_.add(list.get(1));
        list_.add(list.get(2)+list.get(3));
        list_.add(list.get(4));
        list_.add(list.get(5));
        list_.add(list.get(6));
        return JsonResult.success(list_);
    }

    /**
     * 获取订单供应商列表
     * @param query 查询条件
     * @return java.util.List
     * @author ChenLong
     * @date 2021-09-24 15:23:51
     **/
    @GetMapping("getOrderSupplierList")
    public PageUtils<WelfareSupplier> getOrderSupplierList(WelfareOrderQuery query) {
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        query.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.SELF);
        PageInfo<WelfareSupplier> pageInfo = service.getOrderSupplierListPage(query);
        if(pageInfo!=null && pageInfo.getList()!=null && pageInfo.getList().size()>0){
            List<WelfareSupplier> supplierList_ = new ArrayList<>();
            WelfareSupplier welfareSupplier1 = new WelfareSupplier();
            welfareSupplier1.setId(0);
            welfareSupplier1.setName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
            supplierList_.add(welfareSupplier1);
            supplierList_.addAll(pageInfo.getList());
            pageInfo.setList(supplierList_);
        }
        return new PageUtils<>(pageInfo);
    }

    /**
     * 分页查询订单列表（大订单维度）
     * @param query 查询条件
     * @return java.util.List
     * @author ChenLong
     * @date 2021-09-22 15:21:30
     **/
    @GetMapping("getOrderParentListPage")
    public PageUtils<WelfareOrderParentVo> getOrderParentListPage(WelfareOrderQuery query) {
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        //企业端当orderStatus传2待发货时候转成11查待发货+待打款状态的订单
        if(EmptyUtils.isNotEmpty(query.getOrderStatus()) && query.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PAID.getCode()){
            query.setOrderStatus(11);
        }
        if(query.getSupplierId()!=null && query.getSupplierId()==0){
            query.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
            query.setSupplierId(null);
        }
        PageInfo<WelfareOrderParentVo> pageInfo = service.getOrderListPage(query);
        if(EmptyUtils.isNotEmpty(pageInfo) && EmptyUtils.isNotEmpty(pageInfo.getList())){
            pageInfo.getList().forEach(x->{
                if(EmptyUtils.isNotEmpty(x.getChildOrderVoList())){
                    x.getChildOrderVoList().forEach(y->{
                        if(y.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()){
                            y.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
                            y.setOrderStatusName(WelfareOrderEnum.ORDER_STATUS_PAID.getName());
                        }
                        Integer orderGoodsType = y.getOrderGoodsType();
                        if(orderGoodsType == CommonConstants.APP_GOODS_SOURCE.PLAFORM){
                            y.setSupplierName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                        }
                    });
                    /*Integer orderGoodsType = x.getChildOrderVoList().get(0).getOrderGoodsType();
                    if(EmptyUtils.isNotEmpty(orderGoodsType) || orderGoodsType.equals(CommonConstants.APP_GOODS_SOURCE.PLAFORM)){
                        x.setEnterpriseName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                    }*/
                }
            });
        }
        return new PageUtils<>(pageInfo);
    }

    /**
     * 导出全部
     * 以商品为维度导出，一个订单多个商品拆分成多行
     * @param query 搜索条件
     * @return com.dzl.util.JsonResult
     * @date 2021/5/29 14:20
     * @author caobucao
     */
    @GetMapping("exportOrderList")
    public void exportOrderList(WelfareOrderQuery query, HttpServletResponse res, HttpServletRequest req) throws IOException {
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        //企业端当orderStatus传2待发货时候转成11查待发货+待打款状态的订单
        if(EmptyUtils.isNotEmpty(query.getOrderStatus()) && query.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PAID.getCode()){
            query.setOrderStatus(11);
        }
        if(query.getSupplierId()!=null && query.getSupplierId()==0){
            query.setOrderGoodsType(CommonConstants.APP_GOODS_SOURCE.PLAFORM);
            query.setSupplierId(null);
        }
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        List<WelfareOrderSupplierVo> list = service.getOrderChildList(query);
        if(EmptyUtils.isNotEmpty(list)){
            list.forEach(x->{
                if(x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()){
                    x.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
                    x.setOrderStatusName(WelfareOrderEnum.ORDER_STATUS_PAID.getName());
                }
                Integer orderGoodsType = x.getOrderGoodsType();
                if(orderGoodsType == CommonConstants.APP_GOODS_SOURCE.PLAFORM){
                    // x.setEnterpriseName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                    x.setSupplierName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                }
            });
        }
        service.exportOrderList(list, res, req);
    }

    /**
     * 导出选中
     * 以商品为维度导出，一个订单多个商品拆分成多行
     * @param param ids 选中列id
     * @return com.dzl.util.JsonResult
     * @date 2021/5/29 15:35
     * @author caobucao
     */
    @PostMapping("exportOrderListByIds")
    public void exportOrderListByIds(@RequestBody JSONObject param, HttpServletResponse res, HttpServletRequest req) {
        String ids = param.getString("ids");
        if(EmptyUtils.isEmpty(ids)) {
            throw new CommonException("传参有误:ids不能传空");
        }
        WelfareOrderQuery query = new WelfareOrderQuery();
        query.setOrderIds(ids);
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        List<WelfareOrderSupplierVo> list = service.getOrderChildList(query);
        if(EmptyUtils.isNotEmpty(list)){
            list.forEach(x->{
                if(x.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()){
                    x.setOrderStatus(WelfareOrderEnum.ORDER_STATUS_PAID.getCode());
                    x.setOrderStatusName(WelfareOrderEnum.ORDER_STATUS_PAID.getName());
                }
                Integer orderGoodsType = x.getOrderGoodsType();
                if(orderGoodsType == CommonConstants.APP_GOODS_SOURCE.PLAFORM){
                    // x.setEnterpriseName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                    x.setSupplierName(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_NAME);
                }
            });
        }
        service.exportOrderList(list, res, req);
    }

    /**
     * 批量发货
     * @param jsonArray 批量发货入参
     * @return com.dzl.util.JsonResult
     * @date 2021/5/27 17:05
     * @author caobucao
     */
    @PostMapping("batchDelivery")
    public JsonResult<Integer> batchDelivery(@RequestBody JSONArray jsonArray) {
        if (CollectionUtils.isEmpty(jsonArray)) {
            return JsonResult.paramErrWithMsg("请检查有订单编号、物流公司或物流单号未填！");
        }
        List<OrderBatchDeliveryDto> dtoList = jsonArray.toJavaList(OrderBatchDeliveryDto.class);
        return JsonResult.success(service.batchDelivery(dtoList, getAdminInfo()));
    }

    /**
     * 获取订单详情
     * @param orderId 订单id
     * @return com.dzl.util.JsonResult
     * @date 2021/5/28 14:43
     * @author caobucao
     */
    @GetMapping("getOrderDetail")
    public JsonResult<WelfareOrderDetailVo> getOrderDetail(Integer orderId) {
        WelfareOrderDetailVo welfareOrderVo = service.getOrderDetailByOrderId(orderId,CommonConstants.DATA_PORT.COMPANY);
        if(welfareOrderVo!=null && welfareOrderVo.getOrderStatus()==WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()){
            welfareOrderVo.setOrderStatusName(WelfareOrderEnum.ORDER_STATUS_PAID.getName());
        }
        return JsonResult.success(welfareOrderVo);
    }

    /**
     * 取消订单
     * @param welfareOrder 订单对象
     * @return com.dzl.util.JsonResult
     * @date 2021/5/29 17:35
     * @author caobucao
     */
    @PostMapping("cancelOrder")
    public JsonResult<Integer> cancelOrder(@RequestBody WelfareOrder welfareOrder) {
        if (welfareOrder.getOrderType().equals(4)) {
            return JsonResult.paramErrWithMsg("兑换订单不允许取消！");
        }
        welfareOrder.setUpdater(getAdminInfo().getId());
        welfareOrder.setUpdaterName(getAdminInfo().getUserName());
        return JsonResult.success(service.cancelOrder(welfareOrder));
    }

    /**
     * 单订单发货
     * @param jsonArray 发货入参
     * @return com.dzl.util.JsonResult
     * @date 2021/5/27 17:05
     * @author caobucao
     */
    @PostMapping("orderDelivery")
    public JsonResult<Integer> orderDelivery(@RequestBody JSONArray jsonArray) {
        if (CollectionUtils.isEmpty(jsonArray)) {
            return JsonResult.paramErrWithMsg("请检查有订单编号、物流公司、物流单号/备注未填！");
        }
        List<OrderBatchDeliveryDto> dtoList = jsonArray.toJavaList(OrderBatchDeliveryDto.class);
        return JsonResult.success(service.orderDelivery(dtoList, getAdminInfo()));
    }

    /**
     * 订单退款
     * @param welfareOrder 退款订单对象
     * @return com.dzl.util.JsonResult
     * @date 2021/5/31 16:41
     * @author caobucao
     */
    @PostMapping("refundOrder")
    public JsonResult<Integer> refundOrder(@RequestBody WelfareOrder welfareOrder) {
        if (welfareOrder.getOrderType().equals(4)) {
            return JsonResult.paramErrWithMsg("兑换订单不允许退款！");
        }
        welfareOrder.setUpdater(getAdminInfo().getId());
        welfareOrder.setUpdaterName(getAdminInfo().getUserName());
        return JsonResult.success(service.updateRefundOrder(welfareOrder));
    }

    /**
     * 取消订单
     * @param welfareOrderCancelDto 订单取消id
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-06-09 16:05:52
     **/
    @PostMapping(value = "cancelOrderById")
    public JsonResult<Object> cancelOrderById(@RequestBody WelfareOrderCancelDto welfareOrderCancelDto) {
        if (EmptyUtils.isEmpty(welfareOrderCancelDto) || EmptyUtils.isEmpty(welfareOrderCancelDto.getId()) || EmptyUtils.isEmpty(welfareOrderCancelDto.getOrderType())) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        int resCode = service.cancelOrderByOrderId(welfareOrderCancelDto);
        if (resCode != 1) {
            return JsonResult.failWithMsg("操作失败");
        }
        return JsonResult.success();
    }

    /**
     * 更新订单标记
     * @param welfareOrderSignUpdDro 订单标记实体类
     * @return java.lang.Integer
     * @author ChenLong
     * @date 2021-09-22 11:17:29
     **/
    @PostMapping(value = "updateOrderSignDes")
    public JsonResult<Integer> updateOrderSignDes(@RequestBody WelfareOrderSignUpdDro welfareOrderSignUpdDro) {
        if (EmptyUtils.isEmpty(welfareOrderSignUpdDro) || EmptyUtils.isEmpty(welfareOrderSignUpdDro.getOrderId())) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(service.updateOrderRemark(welfareOrderSignUpdDro));
    }

    /**
     * 更新订单地址
     * @param orderAddressUpdDto 订单标记实体类
     * @return java.lang.Integer
     * @author ChenLong
     * @date 2021-09-22 11:17:29
     **/
    @PostMapping(value = "updateOrderAddress")
    public JsonResult<Integer> updateOrderAddress(@RequestBody WelfareOrderAddressUpdDto orderAddressUpdDto) {
        WelfareOrder welfareOrderRes = service.selectByPrimaryKey(orderAddressUpdDto.getOrderId());
        if (EmptyUtils.isEmpty(welfareOrderRes)){
            throw new CommonException("无效的订单");
        }
        if (EmptyUtils.isEmpty(welfareOrderRes.getAddressId())){
            throw new CommonException("无效的订单地址");
        }
        // 只有待发货和待打款的才允许修改
        if (welfareOrderRes.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()) || welfareOrderRes.getOrderStatus().equals(WelfareOrderEnum.ORDER_STATUS_PAID.getCode())){
            WelfareOrderAddress welfareOrderAddressOpt = new WelfareOrderAddress();
            if (EmptyUtils.isEmpty(welfareOrderRes.getAddressId())) {
                return JsonResult.paramErrWithMsg("订单号必录");
            } else {
                welfareOrderAddressOpt.setId(welfareOrderRes.getAddressId());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getName())) {
                return JsonResult.paramErrWithMsg("请填写姓名");
            } else {
                welfareOrderAddressOpt.setName(orderAddressUpdDto.getName());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getPhone())) {
                return JsonResult.paramErrWithMsg("请输入手机号码");
            } else {
                welfareOrderAddressOpt.setPhone(orderAddressUpdDto.getPhone());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getProvince())) {
                return JsonResult.paramErrWithMsg("请选择省份");
            } else {
                welfareOrderAddressOpt.setProvince(orderAddressUpdDto.getProvince());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getCity())) {
                return JsonResult.paramErrWithMsg("请选择城市");
            } else {
                welfareOrderAddressOpt.setCity(orderAddressUpdDto.getCity());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getArea())) {
                return JsonResult.paramErrWithMsg("请选择区域");
            } else {
                welfareOrderAddressOpt.setArea(orderAddressUpdDto.getArea());
            }
            if (EmptyUtils.isEmpty(orderAddressUpdDto.getAddress())) {
                return JsonResult.paramErrWithMsg("请填写详细地址");
            } else {
                welfareOrderAddressOpt.setAddress(orderAddressUpdDto.getAddress());
            }
            welfareOrderAddressOpt.setUpdateTime(new Date());
            return JsonResult.success(welfareOrderAddressService.updateByPrimaryKeySelective(welfareOrderAddressOpt));
        } else{
            throw new CommonException("订单状态已发生改变");
        }
    }

    /**
     * 修改订单供应商
     * @param welfareOrderSupplierUpdDto 订单供应商实体
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-10-13 16:14:11
     **/
    @PostMapping(value = "updateOrderGoodsSupplier")
    public JsonResult<Integer> updateOrderGoodsSupplier(@RequestBody WelfareOrderSupplierUpdDto welfareOrderSupplierUpdDto) {
        if (EmptyUtils.isEmpty(welfareOrderSupplierUpdDto.getId())) {
            throw new CommonException("参数错误");
        }
        if (EmptyUtils.isEmpty(welfareOrderSupplierUpdDto.getNewSupplierId())) {
            throw new CommonException("参数错误");
        }
        service.updateOrderGoodsSupplier(welfareOrderSupplierUpdDto);
        return JsonResult.success();
    }

    /**
     * 修改订单成本价格
     * @param welfareOrderGoodsPriceSingleUpdDto 订单成本价格实体
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-10-13 16:30:20
     **/
    @PostMapping(value = "updateOrderGoodsCostPriceSingle")
    public JsonResult<Integer> updateOrderGoodsCostPriceSingle(@RequestBody WelfareOrderGoodsPriceSingleUpdDto welfareOrderGoodsPriceSingleUpdDto) {
        if (EmptyUtils.isEmpty(welfareOrderGoodsPriceSingleUpdDto.getId())) {
            throw new CommonException("参数错误");
        }
        if (EmptyUtils.isEmpty(welfareOrderGoodsPriceSingleUpdDto.getCostPrice())) {
            throw new CommonException("请填写成本价格");
        }
        WelfareOrderGoods welfareOrderGoodsRes = welfareOrderGoodsService.selectByPrimaryKey(welfareOrderGoodsPriceSingleUpdDto.getId());
        if (EmptyUtils.isEmpty(welfareOrderGoodsRes)){
            throw new CommonException("无效的商品信息");
        }
        WelfareOrderGoods welfareOrderGoodsOpt = new WelfareOrderGoods();
        welfareOrderGoodsOpt.setId(welfareOrderGoodsPriceSingleUpdDto.getId());
        welfareOrderGoodsOpt.setCostPrice(welfareOrderGoodsPriceSingleUpdDto.getCostPrice());
        welfareOrderGoodsOpt.setCostTotalPrice(welfareOrderGoodsPriceSingleUpdDto.getCostPrice().multiply(BigDecimal.valueOf(welfareOrderGoodsRes.getGoodsQuantity())));
        return JsonResult.success(welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsOpt));
    }

    /**
     * 修改订单成本价格
     * @param orderGoodsPriceUpdDto 订单成本价格实体
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-10-13 16:30:20
     **/
    @PostMapping(value = "updateOrderGoodsCostPrice")
    public JsonResult<Integer> updateOrderGoodsCostPrice(@RequestBody WelfareOrderGoodsPriceUpdDto orderGoodsPriceUpdDto) {
        if (EmptyUtils.isEmpty(orderGoodsPriceUpdDto.getId())) {
            throw new CommonException("参数错误");
        }
        if (EmptyUtils.isEmpty(orderGoodsPriceUpdDto.getCostTotalPrice())) {
            throw new CommonException("请填写成本价格");
        }
        WelfareOrderGoods welfareOrderGoodsOpt = new WelfareOrderGoods();
        welfareOrderGoodsOpt.setId(orderGoodsPriceUpdDto.getId());
        welfareOrderGoodsOpt.setCostTotalPrice(orderGoodsPriceUpdDto.getCostTotalPrice());
        return JsonResult.success(welfareOrderGoodsService.updateByPrimaryKeySelective(welfareOrderGoodsOpt));
    }

    /**
     * 批量推送财务打款
     * @date 2021/10/14 15:53
     * @author liuguanjun
     * @param param 订单id等参数
     */
    @PostMapping("/batchPushOrderPayment")
    public JsonResult<Integer> batchPushOrderPayment(@RequestBody WelfareOrderPaymentPushDto param) {
        if(EmptyUtils.isEmpty(param.getOrderIds())) { //供应商_订单id拼接的字符串，格式如：37_1552,36_1553
            return JsonResult.paramErrWithMsg("订单id[orderIds]不能传空");
        }
        if(EmptyUtils.isEmpty(param.getPaymentType())) {
            return JsonResult.paramErrWithMsg("结算类型[paymentType]不能传空");
        }
        if(EmptyUtils.isEmpty(param.getOrderStatus())) {
            return JsonResult.paramErrWithMsg("订单状态[orderStatus]不能传空");
        }
        if(param.getOrderStatus()!= WelfareOrderEnum.ORDER_STATUS_PRE_PAID.getCode()
            && param.getOrderStatus()!=WelfareOrderEnum.ORDER_STATUS_PAID.getCode()
            && param.getOrderStatus()!=WelfareOrderEnum.ORDER_STATUS_SHIPED.getCode()
            && param.getOrderStatus()!=WelfareOrderEnum.ORDER_STATUS_COMPLETED.getCode()){
            return JsonResult.paramErrWithMsg("订单状态[orderStatus]传值有误");
        }
        param.setEnterpriseId(getAdminInfo().getEnterpriseId());
        return JsonResult.success(service.batchPushOrderPayment(param,getAdminInfo()));
    }
}
